<?php
/**
 * 2010-06-10 16:55 Started
 */
require_once('config.php');
require_once('class.twitter.php');
require_once('helper.php');

// Settings
error_reporting(E_ERROR);

$offset = KIN_OFFSET;
$days = array('Mon' => 'Sen', 'Tue' => 'Sel', 'Wed' => 'Rab',
	'Thu' => 'Kam', 'Fri' => 'Jum', 'Sat' => 'Sab', 'Sun' => 'Min');
$attribs = array('id', 'created_at', 'from_user', 'from_user_id',
	'profile_image_url', 'text', 'source', 'to_user_id', 'geo',
	'iso_language_code');
$msg = array(
	'error_connect' => 'Koneksi gagal: ',
	'error_db' => 'Koneksi ke basis data gagal',
	'not_found' => 'Data tidak ditemukan.',
	'pages' => 'Total %1$s kicauan. Laman: ',
	'hide_rt' => 'Sembunyikan RT',
	'show_rt' => 'Tampilkan RT',
	'hide_avatar' => 'Sembunyikan avatar',
	'show_avatar' => 'Tampilkan avatar',
	'error_notag' => 'Data tag belum dimasukkan.',
);

// Open database
$db = mysql_connect(KIN_HOST, KIN_USER, KIN_PASW)
    or die($msg['error_connect'] . mysql_error());
mysql_select_db(KIN_DATA) or die($msg['error_db']);

// Get tags
$query = mysql_query('SELECT * FROM tags WHERE is_active = 1
	ORDER BY priority DESC, tag_code;');
if (mysql_num_rows($query))
    while ($row = mysql_fetch_assoc($query))
        $tags['#' . $row['tag_code']] = array(
			'description' => $row['description'],
			'additional' => $row['additional']
		);
else
	die($msg['error_notag']);

// Process hide RT cookie
if (!isset($_GET['hidert'])) $_GET['hidert'] = $_COOKIE[KIN_COOKIE]['hidert'];
if (!isset($_COOKIE[KIN_COOKIE]['hidert'])) $_GET['hidert'] = '1';
$_GET['hidert'] = ($_GET['hidert'] == '1' ? '1' : '0');
setcookie(KIN_COOKIE . '[hidert]', $_GET['hidert'], time() + KIN_COOKIE_EXP);

// Process hide icon
if (!isset($_GET['hideavatar'])) $_GET['hideavatar'] = $_COOKIE[KIN_COOKIE]['hideavatar'];
if (!isset($_COOKIE[KIN_COOKIE]['hideavatar'])) $_GET['hideavatar'] = '1';
$_GET['hideavatar'] = ($_GET['hideavatar'] == '1' ? '1' : '0');
setcookie(KIN_COOKIE . '[hideavatar]', $_GET['hideavatar'], time() + KIN_COOKIE_EXP);

// Process tag cookie
if (!isset($_GET['tag'])) $_GET['tag'] = $_COOKIE[KIN_COOKIE]['tag'];
if (!isset($_COOKIE[KIN_COOKIE]['tag'])) $_GET['tag'] = 'bahasaku';
$_GET['tag'] = array_key_exists('#' . $_GET['tag'], $tags) ? $_GET['tag'] : 'bahasaku';
setcookie(KIN_COOKIE . '[tag]', $_GET['tag'], time() + KIN_COOKIE_EXP);
$tag = '#' . $_GET['tag'];

// Update based on twitter search
if (!KIN_NOUPDATE)
{
	// Search twitter
	$t = new twitter;
	$s = new summize;
	$stag = $tag;
	if ($tags[$tag]['additional']) $stag .= ' OR ' . $tags[$tag]['additional'];
	$tmp = $s->search($stag, KIN_TWITTER, false, false, $_GET['p'], false);
	$results = $tmp->results;

	// Insert into database and update RT flag
	foreach($results as $d)
	{
		$field = '';
		foreach($attribs as $a)
		{
			if ($a == 'created_at')
				$d->$a = date('Y-m-d H:i', strtotime($d->$a) + $offset);
			$field .= $field ? ', ' : '';
			$field .= $a . ' = ' . quote_sql($d->$a);
		}
		$insert = 'INSERT IGNORE INTO raw SET ' . $field . ';';
		mysql_query($insert);
		$insert = sprintf('INSERT IGNORE INTO tweet_tags (tag_code, tweet_id) ' .
			'VALUES (%1$s, %2$s);', quote_sql($tag), quote_sql($d->id));
		mysql_query($insert);
	}
	mysql_query('UPDATE raw SET is_rt = 1
		WHERE is_rt = 0 AND text LIKE \'%RT %\'');
}

// Compose WHERE condition
$where = 'WHERE a.id = b.tweet_id AND b.tag_code = ' . quote_sql($tag) . ' ';
if ($_GET['hidert'] == '1') $where .= 'AND is_rt = 0 ';
if ($_GET['user'])
	$where2 .= 'AND from_user = ' . quote_sql($_GET['user']);

// Count total record and adjust paging
$query = mysql_query('SELECT COUNT(*) FROM raw a, tweet_tags b ' . $where . $where2);
if(!mysql_num_rows($query))
    $records = 0;
else
{
    $row = mysql_fetch_row($query);
    $records = $row[0];
}
$pages = ceil($records / KIN_DISPLAY);
$page = is_numeric($_GET['p']) ? $_GET['p'] : 1;
if ($page > $pages) $page = $pages;
if ($page < 1) $page = 1;
$_GET['p'] = $page;
$start = ($page - 1) * KIN_DISPLAY;

// Get twit data
$query = mysql_query('SELECT a.* FROM raw a, tweet_tags b ' .
	$where . $where2 . ' ' .
	'ORDER BY id DESC LIMIT ' . $start . ', ' . KIN_DISPLAY);
if (mysql_num_rows($query))
    while($row = mysql_fetch_assoc($query))
        $data[] = $row;

// Get users data
$query = mysql_query('SELECT profile_image_url, from_user,
	COUNT(id) post_count FROM raw a, tweet_tags b ' . $where . '
	GROUP BY profile_image_url, from_user
	ORDER BY 3 DESC, 2 LIMIT 0, 40');
if (mysql_num_rows($query))
    while($row = mysql_fetch_assoc($query))
        $users[] = $row;

mysql_close($db);

$ret .= '<table cellpadding"0" cellspacing="0" width="100%">';
$ret .= '<tr valign="top">';
$ret .= '<td width="80%">';

// Welcome messages
$text = $tags[$tag]['description'];
if ($text)
{
	$text = preg_replace('/(^|\s)@(\w+)/',
		'\1@<a href="http://twitter.com/\2" class="user">\2</a>', $text);
	$ret .= '<p>' . $text . '</p>';
}

// Toggle buttons
$ret .= '<p>';
$ret .= sprintf('<a href="./?hidert=%1$s&user=%3$s">%2$s</a>',
	($_GET['hidert'] == '1' ? '0' : '1'),
	($_GET['hidert'] == '1' ? $msg['show_rt'] : $msg['hide_rt']),
	$_GET['user']
);
$ret .= ' | ';
$ret .= sprintf('<a href="./?hideavatar=%1$s&user=%3$s">%2$s</a>',
	($_GET['hideavatar'] == '1' ? '0' : '1'),
	($_GET['hideavatar'] == '1' ? $msg['show_avatar'] : $msg['hide_avatar']),
	$_GET['user']
);
$ret .= '</p>';

// Show no record or tweet list
if ($records == 0)
{
	$ret .= '<p>' . $msg['not_found'] . '</p>';
}
else
{
	$ret .= paging();

	// Tweets
	$ret .= '<table>';
	foreach($data as $d)
	{

		$date = strtotime($d['created_at']);
		$text = $d['text'];
		$text = preg_replace("#((http|https|ftp)://(\S*?\.\S*?))" .
			"(\s|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie",
			"'<a href=\"$1\" target=\"_blank\" class=\"link\">$1</a>$4'", $text);
		$text = preg_replace('/(^|\s)@(\w+)/',
			'\1@<a href="http://twitter.com/\2" class="user">\2</a>', $text);
		$text = preg_replace('/(^|\s)#(\w+)/',
			'\1<a href="http://twitter.com/search?q=%23\2" class="tag">#\2</a>', $text);

		$ret .= '<tr valign="top"><td>' . ($start + 1 ) . '.';
		$ret .= '</td>';
		if ($_GET['hideavatar'] != '1')
		{
			$ret .= '<td>';
			$ret .= sprintf('<img src="%1$s" ' .
				'height="48" width="48" alt="%2$s" title="%2$s">',
				$d['profile_image_url'], $d['from_user']);
			$ret .= '</td>';
		}
		$ret .= '<td>';
		if (!$_GET['user'])
			$ret .= sprintf('<b><a href="./?user=%1$s">%1$s</a></b> ',
				$d['from_user']);
		$ret .= $text . '<br />';
		$ret .= sprintf('<a href="http://twitter.com/%1$s/statuses/%2$s" ' .
			'class="ts">', $d['from_user'], $d['id']);
		$ret .= $days[date('D', $date)] . ', ';
		$ret .= date('Y-m-d H.i', $date). '';
		$ret .= '</a>';
		$ret .= '</td></tr>';
		$start++;
	}
	$ret .= '</table>';
	$ret .= paging();
}

// Divider
$ret .= '</td><td>&nbsp;</td><td nowrap="nowrap" width="20%">';

// Show top users
foreach($users as $user)
{
	$ret .= sprintf('<img src="%1$s" valign="middle" style="margin: 2px;" ' .
		'height="48" width="48" alt="%2$s" title="%2$s">',
		$user['profile_image_url'], $user['from_user']);
	if ($_GET['user'] == $user['from_user'])
		$ret .= sprintf('<b>%1$s</b>: %2$s',
			$user['from_user'], $user['post_count']);
	else
		$ret .= sprintf('<b><a href="./?user=%1$s">%1$s</a></b>: %2$s',
			$user['from_user'], $user['post_count']);
	$ret .= '<br />';
}

$ret .= '</td>';
$ret .= '</tr>';
$ret .= '</table>';

// Manage header
$title = sprintf('<a href="./">Kintaka</a> ' .
	'<a href="http://twitter.com/search?q=%2$s">%1$s</a>',
	$tag, rawurlencode($tag));
if ($_GET['user'])
	$title .= ' ' . sprintf('<a href="http://twitter.com/%1$s">%1$s</a>',
		$_GET['user']);
if ($_GET['p'] > 1) $title .= ' (' . $page . ')';

$head .= '<form method="get" action="./?">';
$head .= '<table cellpadding"0" cellspacing="0" width="100%">';
$head .= '<tr valign="middle">';
$head .= '<td width="80%">';
$head .= '<h1>' . $title . '</h1>';
$head .= '</td><td width="20%" align="right">';
$head .= '<select id="tag" name="tag" onchange="this.form.submit();">';
foreach ($tags as $key => $value)
{
	$head .= sprintf('<option value="%2$s"%3$s>%1$s</option>',
		$key, substr($key, 1), '#' . $_GET['tag'] == $key ? 'selected' : '');
}
$head .= '</select>';
$head .= '</td>';
$head .= '</tr>';
$head .= '</table>';
$head .= '<input type="hidden" id="user" name="user" value="' .
	$_GET['user'] . '" /></form>';

if (KIN_STAT) $footer = ext_stat();

/**
 * Paging
 *
 * FIXME: Remove global please, you lazy programmer!
 */
function paging()
{
	global $msg, $page, $pages, $records, $_GET;
	$ret .= '<p>';
	$ret .= sprintf($msg['pages'], $records);
	for ($i = 1; $i <= $pages; $i++)
	{
		$ret .= ($i > 1) ? '&nbsp; &nbsp;' : '';
		if ($i == $page)
			$ret .= $i;
		else
			$ret .= sprintf('<a href="./?p=%1$s&user=%2$s">%1$s</a>',
				$i, $_GET['user']);
	}
	$ret .= '</p>';
	return($ret);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo(strip_tags($title)); ?></title>
<style>
body
{
	font-family: 'Trebuchet MS', Helvetica, Sans-Serif;
	font-size: 14px;
}
a { text-decoration: none; }
a:hover { text-decoration: underline; }
a.user { color: #666; }
a.tag { color: #666; }
a.link { color: #666; }
h1 { font-size: 18px; }
.ts { color: #999; font-size: 80% !important; font-variant: italic; }
</style>
</head>
<body>
<?php echo($head); ?></h1>
<?php echo($ret); ?>
<p><a href="http://code.google.com/p/kintaka/">Kintaka 0.1</a> |
	<a href="./LICENSE.TXT">GPL 2</a></p>
<?php echo($footer); ?>
</body>
</html>